package com.biqee.util;

import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class MapUtil {
	
	/**
	 * 将一个bean转换成map
	 * 
	 * @param map
	 * @param bean
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map populateMap(Map map, Object bean) {
		return populateMap(map, bean, null);
	}

	/**
	 * 将一个bean转换成map
	 * 
	 * @param map
	 * @param bean
	 * @param prefix
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map populateMap(Map map, Object bean, String prefix) {
		boolean nonPrefix = StringUtils.isBlank(prefix);

		try {
			Method[] methods = bean.getClass().getMethods();
			for (int i = 0; i < methods.length; i++) {
				String methodName = methods[i].getName();
				Class[] pts = methods[i].getParameterTypes();
				Class rt = methods[i].getReturnType();

				if ((methodName.startsWith("get") || methodName
						.startsWith("is"))
						&& pts.length == 0 && !Void.class.equals(rt)) {
					String propName = (methodName.startsWith("is")) ? Character
							.toLowerCase(methodName.charAt(2))
							+ methodName.substring(3) : Character
							.toLowerCase(methodName.charAt(3))
							+ methodName.substring(4);
					String key = nonPrefix ? propName : prefix + propName;

					Object value = methods[i].invoke(bean, new Object[] {});
					map.put(key, value);
				}
			}
			return map;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


}